package DAO;

import Utils.HibernateUtil;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import model.Category;
import model.User;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionException;
import org.hibernate.Transaction;
import validator.e;

public class CategoryDaoImp implements CategoryDao{

     public List<Category> listCategory(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        Query query= session.createSQLQuery("select * from Category").addEntity(Category.class);
        List list = query.list();
        session.close();
        return list;
        }
     
     public void save(Category category){
     Session session = HibernateUtil.getSessionFactory().openSession(); 
     Transaction t = session.beginTransaction();        
     
     if(consultCategory(category.getName())){
     try{
        session.save(category);
        t.commit();
        e.exibirMsgSucesso("Sucess");
     }
     catch(HibernateException err){
         e.exibirMsgErro("Error - Try Again");
     }}
     else{
         e.exibirMsgErro("Duplicate Name");
     }
     session.close();
 }
     
     public void update(Category category) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        Category c = new Category();
        c.setCategory_id((category.getCategory_id()));
        c.setGoal(category.getGoal());
        c.setName(category.getName());
        try{
        session.update(c);
        t.commit();
        e.exibirMsgSucesso("Sucess");
        }
        catch(HibernateException err){
            e.exibirMsgErro("Error");
        }
        session.close();
    }
     
     public void remove(Category category) throws HibernateException {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        try{
        session.delete(category);
        t.commit();
        e.exibirMsgSucesso("Sucess");
        }catch(HibernateException err){
            e.exibirMsgErro("Error - Could not delete the category");
        }
        session.close();
    }
     
     public boolean consultCategory(String name){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        Query query= session.createSQLQuery("select * from Category where name = :name").addEntity(Category.class);
        query.setParameter("name",name);
        List lista = query.list();
        if(lista == null || lista.isEmpty()){
            return true;
        }else{
            return false;
        }
    }
}
